<?php
/**
 * 诊所管理
 * Created by PhpStorm.
 * User: dower
 * Date: 2016/7/26 0026
 * Time: 下午 15:31
 */
namespace Doctor\Controller\Clinic;

use Doctor\Model\Clinic\ClinicModel;
use Doctor\Model\Doctor\DoctorModel;
use Doctor\Controller\BaseController;
use Home\Common\SalemanagerHelper;
use Home\Common\SalemanHelper;
class ClinicController extends BaseController{

    public $model = null;
    public $model2 = null;
    private $size = 10;
    public $userinfo = null;

    public function __construct()
    {
        parent::__construct();
        $this->handleLogin(true);//该控制器所以操作均要求登录情况下
        $this->model = new ClinicModel();
        $this->model2 = new DoctorModel();
    }

    /**
     * 诊所首页
     */
    public function index(){
        if($this->userinfo['login_type']==1){//非管理员
            $clinic_id = $this->userinfo['clinic_id'];
            //得到诊所信息
            $clinic = M('Clinic')->find($clinic_id);
            //诊所头像
            $clinic['image'] = array_shift(explode(',',$clinic['clinic_pic']));
            //执业资质图片集
            $clinic['imgs'] = explode(',',$clinic['clinic_licence']);
            //得到所有的医生信息
            $doctors = M('Doctor')->field('id,name,good,score')->where(array('clinic_id'=>$clinic_id,'status'=>0))->order('score desc')->select();
            $this->assign('doctors', $doctors);
            $doctor_ids = array_column($doctors,'id');
            $this->assign('ids', implode(',',$doctor_ids));
            //得到诊断量
            $clinic['treat_num'] = 0;
            if($doctors){
                $clinic['treat_num'] = M('DoctorTreatment')->where(array('doctor_id'=>array('in',$doctor_ids)))->count();
            }
            $this->assign('clinic', $clinic);
            //得到诊所的评论信息
            $assess = array('count'=>0,'rows'=>array());
            if($doctors){
                $where = array(
                    'a.doctor_id'=>array('in',$doctor_ids)
                );
                $assess = $this->model2->assessList($where,$this->size);
            }
            $this->assign('size', $this->size);
            $this->assign('list', $assess['rows']);
            $this->assign('count',$assess['count']);
            //设置头部
            $my_header = array(
                'back'=>0,
                'header'=>true,
                'header1'=>'诊所',
                'header2'=>false,
                'footer'=>true,
                'footer1'=>'clinic',
            );
            $display = 'no_clinic';
        }else{//管理员
            $this->assign('userinfo', $this->userinfo);
            //设置头部
            $my_header = array(
                'back'=>0,
                'header'=>true,
                'header1'=>$this->userinfo['clinic_name'],
                'header2'=>false,
                'footer'=>true,
                'footer1'=>'clinic',
            );
            $display = 'clinic';
        }
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display($display);
    }
    public function order()
    {   
         if (IS_AJAX) {

            $op = $_GET['op'];
            switch ($op) {
                //执行药品下拉加载的方法
                case 'list':
                    //获取每页显示条数
                    $limit = C('DEF_LIMIT');

                    //获取传递参数
                    $page = $_POST['page'];
                    if (!is_numeric($page) || intval($page) < 0) {
                        $page = 0;
                    }

                    $where = array(
                        'is_valid' => array('eq', 1)
                    );
                    $order = array(
                        'sort'
                    );

                    //查询总记录
                    $drugsModel = M('drugs');
                    $count = $drugsModel->where($where)->count();
                    //获取总页数
                    if (intval($count % $limit) > 0) {
                        $totalPage = intval($count / $limit) + 1;
                    } else {
                        $totalPage = intval($count / $limit);
                    }
                    if ($page > $totalPage) {
                        responseJson(0, '暂无更多记录');
                        exit;
                    }

                    $startNum = $page * $limit;

                    //查询
                    $drugsList = $drugsModel->where($where)->order($order)->select();
                   
                    if (!check_array($drugsList)) {
                        responseJson(0, '暂无更多记录');
                        exit;
                    }

                    //返回数据
                    responseJson(1, 'success', $drugsList);
                    exit;

                    break;

                default:
                    break;
            }
            exit;
        }
        //查询购物车信息

        $drugsCartModel = M('drugs_cart');
        $where = array(
            'add_user_id' => array('eq', UID),
            'type' => array('eq', 0)
        );

       
        $drugsCartList = $drugsCartModel->where($where)->select();
        
        $cartList = array(
            'num' => 0,
            'total_price' => 0
        );

        if (check_array($drugsCartList)) {
            //获取所有药品ID集合
            $drugsIdList = array_keys(set_array_key($drugsCartList, 'drugs_id'));

            //查询药品集合信息
            $drugsModel = M('drugs');
            $where = array(
                'id' => array('in', $drugsIdList)
            );
            $field = array(
                'id', 'price'
            );
            $drugsList = $drugsModel->where($where)->field($field)->select();
            $drugsList = set_array_key($drugsList, 'id');

            foreach ($drugsCartList as $key => $value) {
                $price = isset($drugsList[$value['drugs_id']]) ? $drugsList[$value['drugs_id']]['price'] : 0;
                $totalPrice = $value['num'] * $price;
                $cartList['num']+=$value['num'];
                $cartList['total_price']+=$totalPrice;
            }
        }
        foreach($drugsCartList as $key=>$val)
        {
              $drugsCartList[$key]['price'] = M("drugs")->where("id=".$val['drugs_id'])->getField("price");
        }

        $this->assign("mess",$cartList);
        $this->assign('list',$drugsCartList);
        

        $this->display("drugOrder");
    }
    public function number()
    {
           if(IS_AJAX)
           {
              $drugs_id = $_POST['drugs_id'];
              $type = $_POST['type'];
              $number =  M('drugs_cart')->where("add_user_id=".UID." and drugs_id=".$drugs_id)->getField("num");
              if($type=="add")
              {
                 ++$number;
              }else if($type=="jian")
              {
                 --$number;
              }
              $flag = M("drugs_cart")->where("add_user_id=".UID." and drugs_id=".$drugs_id)->save(array('num'=>$number));
              if($flag)
              {
                  $res = M("drugs_cart")->where("add_user_id=".UID)->field("drugs_id,num")->select();
                  $total_price = 0;
                  foreach($res as $key=>$val)
                  {
                      $total_price+=M("drugs")->where("id=".$val['drugs_id'])->getField("price")*$val['num'];
                  }

                  $this->ajaxReturn(array('code'=>1,'number'=>$number,'price'=>$total_price));
              }else{
                  $this->ajaxReturn(array('code'=>0));
              }
           }
    }
      public function setelOrder() {

        if (IS_AJAX) {
            $op = $_GET['op'];
            switch ($op) {
                //删除购物车药品
                case 'delete':
                    $drugsId = $_POST['drugs_id'];

                    //查询购物车是否存在指定药品的信息
                    $drugsCartModel = M('drugs_cart');
                    $where = array(
                        'add_user_id' =>UID,
                        'type' => 0,
                        'drugs_id' => array('eq', $drugsId)
                    );
                    $cart = $drugsCartModel->where($where)->find();
                    if (!check_array($cart)) {
                        responseJson(0, '删除失败');
                        exit;
                    }

                    //删除
                    $excNum = $drugsCartModel->where($where)->delete();
                    if ($excNum <= 0) {
                        responseJson(0, '删除失败');
                        exit;
                    }

                    responseJson(1, '删除成功');
                    exit;
                    break;
                //提交订单
                case 'submit':
                    $address = $_POST['address'];
                    if (empty($address)) {
                        responseJson(0, '请填写地址');
                        exit;
                    }
					
                    //常用地址管理
                    //1.查找数据重复问题
                    $commonArray = array(
                    		'address'=>$address,
                    		'saleman_id'=>UID,
                    		'send_type' =>0
                    );
                    if(empty(M('common_address')->where($commonArray)->find())){
                    	$return = M('common_address')->add($commonArray);
                    };
                    
                    //查询当前用户购物车里的信息集合
                    $drugsCartModel = M('drugs_cart');
                    $where = array(
                        'add_user_id' => UID,
                        'type' => 0
                    );
                    $cartList = $drugsCartModel->where($where)->select();
                    if (!check_array($cartList)) {
                        responseJson(0, '购物车里暂无药品');
                        exit;
                    }

                    //获取药品ID集合
                    $cartList = set_array_key($cartList, 'drugs_id');
                    $drugsIdList = array_keys($cartList);

                    //查询购物车里药品信息
                    $drugsModel = M('drugs');

                    $where = array(
                        'id' => array('in', $drugsIdList),
                        'is_valid' => array('eq', 1)
                    );
                    $drugsList = $drugsModel->where($where)->select();
                    if (!check_array($drugsList)) {
                        responseJson(0, '购物车里暂无有效药品');
                        exit;
                    }

                    //组装有效药品集合和药品总金额和总数量
                    $dataDrugsList = array();
                    $totalPrice = 0;
                    $totalNum = 0;
                    foreach ($drugsList as $key => $value) {
                        $drugsNum = $cartList[$value['id']]['num'];
                        $drugsPrice = $drugsNum * $value['price'];
                        $totalPrice+=$drugsPrice;
                        $totalNum+=$drugsNum;
                        $dataDrugsList[] = array(
                            'drugs_id' => $value['id'],
                            'drugs_name' => $value['name'],
                            'price' => $value['price'],
                            'num' => $drugsNum,
                            'total_price' => $drugsPrice
                        );
                    }
                    //开启事务
                    $drugsCartModel->startTrans();

                    //清空购物车
                    $cartIdList = array_keys(set_array_key($cartList, 'id'));
                    $where = array(
                        'id' => array('in', $cartIdList)
                    );
                    $delNum = $drugsCartModel->where($where)->delete();
                    if ($delNum != count($cartList)) {

                        $drugsCartModel->rollback();
                        responseJson(0, '订单提交失败');
                        exit;
                    }

                    //获取订单ID
                    $date = date('Y-m-d');
                    $orderId = SalemanHelper::makeOrderId($date);

                    //添加订单
                    $salemanOrderModel = M('saleman_order');
                    $data = array(
                        'id' => $orderId,
                        'send_id' => UID,
                        'type' => 0,//0表示是诊所发送的订单
                        'status' => 0,
                        'saleman_id' => M("clinic")->where("id=".UID)->getField("saleman_id"),
                        'total_price' => $totalPrice,
                        'num' => $totalNum,
                        'add_date' => $date,
                        'add_time' => time(),
                        'address' => $address
                    );

                    

                    $excNum = $salemanOrderModel->add($data);
                    
                    if ($excNum <= 0) {
                        $drugsCartModel->rollback();
                        responseJson(0, '订单提交失败');
                        exit;
                    }


                    //添加订单详情
                    $salemanOrderDetailModel = M('saleman_order_detail');
                    foreach ($dataDrugsList as $key => $value) {
                        $data = array(
                            'order_id' => $orderId,
                            'drugs_id' => $value['drugs_id'],
                            'drugs_name' => $value['drugs_name'],
                            'price' => $value['price'],
                            'num' => $value['num'],
                            'total_price' => $value['total_price'],
                            'add_time' => time()
                        );
                        $excNum = $salemanOrderDetailModel->data($data)->add();
                        if ($excNum <= 0) {
                            $drugsCartModel->rollback();
                            responseJson(0, '订单提交失败');
                            exit;
                        }
                    }

                    //提交事务
                    $drugsCartModel->commit();

                    //返回
                    responseJson(1, '订单提交成功');
                    exit;
                    break;
                default:
                    break;
            }
            exit;
        }

        //查询当前用户购物车信息
        $drugsCartModel = M('drugs_cart');
        $where = array(
            'add_user_id' =>UID,
            'type' => 0
        );
        $cartList = $drugsCartModel->where($where)->select();
        $totalPrice = 0;

        if (is_array($cartList)) {
            //获取所有的药品ID集合
            $drugsIdList = array_keys(set_array_key($cartList, 'drugs_id'));

            //查询药品集合
            $drugsModel = M('drugs');
            $where = array(
                'id' => array('in', $drugsIdList)
            );
            $field = array(
                'id', 'name', 'price', 'is_valid'
            );
            $drugsList = $drugsModel->field($field)->where($where)->select();
            $drugsList = set_array_key($drugsList, 'id');

            //组装数据
            foreach ($cartList as $cart_key => $cart_value) {
                if (!isset($drugsList[$cart_value['drugs_id']]) || $drugsList[$cart_value['drugs_id']]['is_valid'] != 1) {
                    unset($cartList[$cart_key]);
                    continue;
                }
                $cartList[$cart_key]['price'] = $drugsList[$cart_value['drugs_id']]['price'];
                $cartList[$cart_key]['totalPrice'] = $drugsList[$cart_value['drugs_id']]['price'] * $cart_value['num'];
                $totalPrice+=$cartList[$cart_key]['totalPrice'];
            }
        }
        $address = M("common_address")->where("saleman_id=".UID." and send_type=0")->field("address")->order("id DESC")->limit(0,5)->distinct(true)->select();
        
        $this->assign(array(
            'cartList' => $cartList,
            'totalPrice' => $totalPrice,
            'address'=>$address
        ));

        $this->assign("list",$cartList);
        $this->display("sete");
    }
    public function clinicorder()
    {
         $status = isset($_GET['status'])?$_GET['status']:0;
         $where = "";
         if(!isset($_GET['status']))
         {
           $where.= "ymt_saleman_order.send_id=".UID." and ymt_saleman_order.type=0";
         }else if(isset($_GET['status']))
         {

            $where.= "ymt_saleman_order.send_id=".UID."  and ymt_saleman_order.status=".$status." and ymt_saleman_order.type=0";
         }
         
         //$result = M("saleman_order")->where("ymt_saleman_order.send_id=".UID." and ymt_saleman_order.status=".$status." and ymt_saleman_order.type=1")->join("ymt_saleman_order_detail on ymt_saleman_order_detail.order_id=ymt_saleman_order.id")->order("ymt_saleman_order.add_time DESC")->group('ymt_saleman_order.id')->select();
         $result = M("saleman_order")->where($where)->order("ymt_saleman_order.add_time DESC")->group('ymt_saleman_order.id')->select();
         foreach($result as $key=>$val)
         {
         		$drug_id = M('saleman_order_detail')->where('order_id='.$val['id'])->getField("drugs_id");
              	$drug = M("drugs")->field("cover_img,name")->where("id=".$drug_id)->find();
              	$result[$key]['img']=$drug['cover_img'];
              	$result[$key]['drugs_name']=$drug['name'];
         }

         $this->assign("list",$result);
         $this->display();

    }
    public function orderdetail()
    {
        $id = $_GET['id'];
        $address = M("saleman_order")->where("id=".$id)->field("total_price,address,status")->find();
        $detail = M("saleman_order_detail")->where("order_id=".$id)->select();
        $this->assign("list",$detail);
        $this->Assign("address",$address);
        $this->display("detail");
    }
    public function details()
    {
           if (IS_AJAX) {

            $drugsId = $_POST['drugs_id'];
            $num = $_POST['num'];
            if (empty($drugsId)) {
                responseJson(0, '加入购物车失败');
                exit;
            }

            if (!is_numeric($num) || $num <= 0) {
                $num = 1;
            }

            //查询当前药品是否
            $drugsModel = M('drugs');
            $where = array(
                'id' => array('eq', $drugsId)
            );
            $drugs = $drugsModel->where($where)->find();
            if (!check_array($drugs)) {
                responseJson(0, '加入购物车失败');
                exit;
            }

            //查询当前药品是否已存在购物车中
            $drugsCartModel = M('drugs_cart');
            $where = array(
                'add_user_id' => UID,
                'type' => array('eq', 0),
                'drugs_id' => array('eq', $drugsId)
            );
            $cart = $drugsCartModel->where($where)->find();

            if (check_array($cart)) {
                //修改数量
                $data = array(
                    'num' => $cart['num'] + 1,
                    'add_time' => time()
                );
                $excNum = $drugsCartModel->where($where)->data($data)->save();
            } else {
                //新增
                $data = array(
                    'add_user_id' => UID,
                    'type' => 0,
                    'drugs_id' => $drugsId,
                    'drugs_name' => $drugs['name'],
                    'num' => $num,
                    'add_time' => time()
                );
              
                $excNum = $drugsCartModel->data($data)->add();
            }
            if ($excNum <= 0) {
                responseJson(0, '加入购物车失败');
                exit;
            }

            responseJson(1, '加入购物车成功');
            exit;
        }

        $id = $_GET['id'];
        //查询药品详情
        $drugsModel = M('drugs');
        $where = array(
            'id' => array('eq', $id),
            'is_valid' => array('eq', 1)
        );
        $drugs = $drugsModel->where($where)->find();
        
          $this->assign('drugs', $drugs);
          $this->display("odetail");
    }
    /*
     * 得到诊所的更多评价
     */
    public function no_clinic_more(){
        //添加查询条件
        $ids = I('get.ids');
        $where = array();
        if($ids){
            $where['a.doctor_id'] =array('in',$ids);
        }
        //得到列表
        $list = $this->model2->assessList($where,$this->size);
        $this->assign('list', $list['rows']);
        //加载视图
        $this->display('no_clinic_more');
    }

    /**
     * 医生管理
     */
    public function doctor(){
        //得到医生信息
        $doctors = M('Doctor')->field('id,name,good,mobile,score')->where(array('clinic_id'=>UID,'status'=>0))->order('CONVERT(name USING gbk) asc')->select();//按姓名排序
        $this->assign('doctors', $doctors);
        //渲染页面
        $this->assign('doctors',$doctors);
        $this->assign('clinic_name',$this->userinfo['clinic_name']);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'医生管理',
            'header3'=>'添加医生',
            'header4'=>U('add_doctor'),
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('doctor.index');
    }

    /**
     * 添加医生
     */
    public function add_doctor(){
        if(IS_POST){
            $requestData = I('post.');
            $res = $this->model->add_doctor($requestData);
            if($res){
                $this->ajaxReturn(array('code'=>0,'url'=>U('doctor')));
            }else{
                $this->ajaxReturn(array('code'=>1,'msg'=>$this->model->getError()));
            }
        }else{
            //设置头部
            $my_header = array(
                'header'=>true,
                'header1'=>'添加医生',
            );
            $my_header = array_merge($this->header,$my_header);
            $this->assign($my_header);
            //加载视图
            $this->display('doctor.add');
        }
    }

    /**
     * 医生详情
     * @param $id int 医生id
     */
    public function view_doctor($id){
        //得到医生信息
        $doctor = M('Doctor')->find($id);
        //身份证图
        if(empty($doctor['id_image'])==false){
            $doctor['imgs'] = explode(',',$doctor['id_image']);
        }
        $this->assign('doctor',$doctor);
        $this->assign('userinfo',$this->userinfo);
        //得到医生评价数据
        $where = array(
            'a.doctor_id'=>$id
        );
        $assess = $this->model2->assessList($where,$this->size);
        $this->assign('size', $this->size);
        $this->assign('list', $assess['rows']);
        $this->assign('count',$assess['count']);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'医生主页',
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('doctor.view');
    }

    /**
     * 得到医生的更多评价
     * @param $id int 医生id
     */
    public function view_doctor_more($id){
        //添加查询条件
        $where['a.doctor_id'] =$id;
        //得到列表
        $list = $this->model2->assessList($where,$this->size);
        $this->assign('list', $list['rows']);
        //加载视图
        $this->display('doctor.view_more');
    }

    /**
     * 删除医生
     * @param $id
     */
    public function delete_doctor($id){
        //判断医生为当前诊所的
        $rst = M('Doctor')->where(array('clinic_id'=>UID,'id'=>$id))->count();
        if(!$rst) $this->ajaxReturn(array('code'=>2,'msg'=>'网络繁忙, 请稍后再试'));
        //删除医生
        $res = $this->model->delete_doctor($id);
        if($res){
            $this->ajaxReturn(array('code'=>0,'url'=>U('doctor')));
        }else{
            $this->ajaxReturn(array('code'=>1,'msg'=>$this->model->getError()));
        }
    }

    /**
     * 患者管理
     */
    public function patient(){
        //得到患者列表
        //得到诊所的医生id
        $ids = $this->getDoctorIds();
        $where = array(
            'a.doctor_id'=>array('in',$ids)
        );
        $res = $this->model->patientList($where);
        $this->assign('size', $this->size);
        $this->assign('list', $res['rows']);
        $this->assign('count',$res['count']);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'我的患者',
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('patient.index');
    }

    /**
     * 患者管理-更多
     */
    public function patient_more(){
        //得到患者列表
        //得到诊所的医生id
        $ids = $this->getDoctorIds();
        $where = array(
            'a.doctor_id'=>array('in',$ids)
        );
        $res = $this->model->patientList($where);
        $this->assign('list', $res['rows']);
        $this->display('patient.index_more');
    }

    /**
     * 患者详情
     * @param $id
     */
    public function view_patient($id){
        //得到患者信息
        $patient = M('Patient')->find($id);
        $this->assign('patient',$patient);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'患者详情',
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('patient.view');
    }

    /**
     * 患者详情--字多的
     * @param $id
     * @param $type
     */
    public function todetail($id,$type){
        //标题
        $name = '';
        //得到内容
        $id = intval($id);
        $content = M('Patient')->where(array('id'=>$id))->getField($type);
        //渲染页面
        $this->assign('name',$name);
        $this->assign('content',$content);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'查看详情',
            'header3'=>'',
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('patient.todetail');
    }

    /**
     * 资料管理
     */
    public function info(){
        if(IS_POST){
            //保存信息
            $data = I('post.');
            //处理诊所图片
            $rst = $this->model2->handleImage($data['imgs'],'clinic');
            if($rst===false){
                $this->ajaxReturn(array('code'=>1,'msg'=>'保存图片失败'));
            }
            $data['clinic_pic'] = implode(',',$rst);
            unset($data['imgs']);
            //处理资质图片
            $rst = $this->model2->handleImage($data['licences'],'clinic');
            if($rst===false){
                $this->ajaxReturn(array('code'=>1,'msg'=>'保存图片失败'));
            }
            $data['clinic_licence'] = implode(',',$rst);
            unset($data['licences']);
            //保存信息
            $res = M('Clinic')->where('id='.UID)->save($data);
            if($res!==false){
                //信息修改,情况userinfo
                session('userinfo', null);
                $this->ajaxReturn(array('code'=>0,'url'=>U('info')));
            }else{
                $this->ajaxReturn(array('code'=>1,'msg'=>'保存失败'));
            }
        }else{
            //设置诊所信息
            $userinfo = $this->getLastInfo();
            if($userinfo['clinic_pic']){
                $userinfo['imgs'] = explode(',',$userinfo['clinic_pic']);
            }
            if($userinfo['clinic_licence']){
                $userinfo['licence'] = explode(',',$userinfo['clinic_licence']);
            }
            $this->assign('userinfo',$userinfo);
            //设置头部
            $my_header = array(
                'header'=>true,
                'header1'=>'诊所详情',
            );
            $my_header = array_merge($this->header,$my_header);
            $this->assign($my_header);
            //加载视图
            $this->display('info.index');
        }
    }

    /**
     * 诊所负责人资料
     */
    public function manager(){
        if(IS_POST){
            //保存负责人信息
            $data = I('post.');
            //处理身份证图片
            $rst = $this->model2->handleImage($data['imgs'],'dcotor');
            if($rst===false){
                $this->ajaxReturn(array('code'=>1,'msg'=>'保存图片失败'));
            }
            $data['id_image'] = implode(',',$rst);
            unset($data['imgs']);
            //保存信息
            $res = M('Doctor')->where('id='.$this->userinfo['did'])->save($data);
            if($res!==false){
                //信息修改,情况userinfo
                session('userinfo', null);
                $this->ajaxReturn(array('code'=>0));
            }else{
                $this->ajaxReturn(array('code'=>1,'msg'=>'保存失败'));
            }
        }else{
            $info = M('Doctor')->find($this->userinfo['did']);
            //处理身份证图片
            if(empty($info['id_image'])==false){
                $info['imgs'] = explode(',',$info['id_image']);
            }
            $this->assign('info',$info);
            //设置头部
            $my_header = array(
                'header'=>true,
                'header1'=>'诊所负责人资料',
            );
            $my_header = array_merge($this->header,$my_header);
            $this->assign($my_header);
            //加载视图
            $this->display('info.doctor');
        }
    }

    /**
     * 患者评价
     */
    public function assess(){
        //得到所有的医生id
        $doctor_ids = $this->getDoctorIds();
        $where = array('a.doctor_id'=>array('in',$doctor_ids));
        //筛选分数
        $score = I('get.score',0);
        if(!empty($score)) $where['a.score'] = $score;
        //得到列表
        $list = $this->model2->assessList($where,$this->size);
        $this->assign('size', $this->size);
        $this->assign('list', $list['rows']);
        $this->assign('count',$list['count']);
        $this->assign('score',$score);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'患者评价',
            'header3'=>'评价数据',
            'header4'=>U('assesscount'),
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('assess.list');
    }

    /**
     * 患者评价-更多
     */
    public function assess_more(){
        //得到所有的医生id
        $doctor_ids = $this->getDoctorIds();
        $where = array('a.doctor_id'=>array('in',$doctor_ids));
        //筛选分数
        $score = I('get.score',0);
        if(!empty($score)) $where['a.score'] = $score;
        //得到列表
        $list = $this->model2->assessList($where,$this->size);
        $this->assign('list', $list['rows']);
        //加载视图
        $this->display('assess.list_more');
    }

    /**
     * 评价数据
     */
    public function assesscount(){
        //得到所有的医生id
        $doctor_ids = $this->getDoctorIds();
        $where = array('doctor_id'=>array('in',$doctor_ids));
        //得到总数
        $total = $this->model2->assessData($where);
        //得到每月的分析数据
        $date = I('get.date');
        $date = $date?:date('Y-m');//默认为当前月
        $count = $this->model2->assessData($where,2,$date);
        $this->assign('total',$total);
        $this->assign('count',$count);
        $this->assign('date',$date);
        //设置头部
        $my_header = array(
            'h_title'=>'诊疗数据',
            'header'=>true,
            'header1'=>'诊疗数据',
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('assess.count');
    }

    /**
     * ajax获得月份数量
     * @param $date
     */
    public function getAssessCount($date){
        //得到所有的医生id
        $doctor_ids = $this->getDoctorIds();
        //筛选条件
        $where = array('doctor_id'=>array('in',$doctor_ids));
        //查询数量
        $date = $date?:date('Y-m');//默认为当前月
        $count = $this->model2->assessData($where,2,$date);
        $this->ajaxReturn(array('code'=>1,'data'=>$count));
    }

    /**
     * 诊疗记录
     */
    public function treatment(){
        //添加查询条件
        $name = I('get.name');
        if($name!==''){
            $where['b.name'] = array('like','%'.$name.'%');
        }
        //得到所有的医生id
        $doctor_ids = $this->getDoctorIds();
        //筛选条件
        $where['a.doctor_id'] = array('in',$doctor_ids);
        //得到列表
        $list = $this->model2->treatmentlist($where,$this->size);
        $this->assign('size', $this->size);
        $this->assign('count', $list['count']);
        $this->assign('list', $list['rows']);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'诊疗记录',
            'header3'=>'诊疗数据',
            'header4'=>U('treatmentcount'),
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('treatment.list');
    }

    /**
     * 诊疗记录-更多
     */
    public function treatment_more(){
        //添加查询条件
        $name = I('get.name');
        if($name!==''){
            $where['b.name'] = array('like','%'.$name.'%');
        }
        //得到所有的医生id
        $doctor_ids = $this->getDoctorIds();
        //筛选条件
        $where['a.doctor_id'] = array('in',$doctor_ids);
        //得到列表
        $list = $this->model2->treatmentlist($where,$this->size);
        $this->assign('list', $list['rows']);
        //加载视图
        $this->display('treatment.list_more');
    }

    /**
     * 诊疗数据
     */
    public function treatmentcount(){
        //查询总量
        //得到所有的医生id
        $doctor_ids = $this->getDoctorIds();
        //筛选条件
        $where['doctor_id'] = array('in',$doctor_ids);
        $total = M('DoctorTreatment')->where($where)->count();
        //添加查询条件
        $date = I('get.date');
        $ids = implode(',',$doctor_ids);
        $date = $date?:date('Y-m');//默认为当前月
        $sql = "select count(*) as count from __PREFIX__doctor_treatment where `doctor_id` in (".$ids.") and DATE_FORMAT(`treat_time`, '%Y-%m')='{$date}'";
        $rst = M('DoctorTreatment')->query($sql);
        $count = 0;
        if($rst){
            $count = $rst[0]['count'];
        }
        $this->assign('date',$date);
        $this->assign('total',$total);
        $this->assign('count',$count);
        //设置头部
        $my_header = array(
            'h_title'=>'诊疗数据',
            'header'=>true,
            'header1'=>'诊疗数据',
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('treatment.count');
    }

    /**
     * ajax获得月份数量
     * @param $date
     */
    public function getTreatmentCount($date){
        $doctor_ids = $this->getDoctorIds();
        $ids = implode(',',$doctor_ids);
        //查询数量
        $date = $date?:date('Y-m');//默认为当前月
        $sql = "select count(*) as count from __PREFIX__doctor_treatment where `doctor_id` in (".$ids.") and DATE_FORMAT(`treat_time`, '%Y-%m')='{$date}'";
        $rst = M('DoctorTreatment')->query($sql);
        $count = 0;
        if($rst){
            $count = $rst[0]['count'];
        }
        $this->ajaxReturn(array('code'=>0,'data'=>$count));
    }

    /**
     * 得到诊所的医生id数组
     * @return array
     */
    private function getDoctorIds(){
        $doctor_ids = S('my_doctor_ids_'.UID);
        if(empty($doctor_ids)){
            $doctors = M('Doctor')->field('id')->where(array('clinic_id'=>UID,'status'=>0))->select();
            if($doctors){
                $doctor_ids = array_column($doctors,'id');
            }else{
                $doctor_ids = array(0);
            }
            S('my_doctor_ids_'.UID,$doctor_ids,C('MY_CACHE_TIME'));//缓存结果
        }
        return $doctor_ids;
    }

    /**
     * 活动管理
     */
    public function activity(){
        //得到医生信息
        $activitys = M('Activity')->field('id,activity_name,activity_time,activity_require,activity_limit,activity_place,create_time')->where(array('clinic_id'=>UID))->order('create_time desc')->select();//按添加时间排序
        //渲染页面
        $this->assign('activitys',$activitys);
        $this->assign('clinic_name',$this->userinfo['clinic_name']);
        //设置头部
        $my_header = array(
            'header'=>true,
            'header1'=>'活动管理',
            'header3'=>'添加活动',
            'header4'=>U('add_activity'),
        );
        $my_header = array_merge($this->header,$my_header);
        $this->assign($my_header);
        //加载视图
        $this->display('activity.index');
    }

    /**
     * 添加活动
     */
    public function add_activity(){
        if(IS_POST){
            $requestData = I('post.');
            $res = $this->model->add_activity($requestData);
            if($res){
                $this->ajaxReturn(array('code'=>0,'url'=>U('activity')));
            }else{
                $this->ajaxReturn(array('code'=>1,'msg'=>$this->model->getError()));
            }
        }else{
            //设置头部
            $my_header = array(
                'header'=>true,
                'header1'=>'添加活动',
            );
            $my_header = array_merge($this->header,$my_header);
            $this->assign($my_header);
            //加载视图
            $this->display('activity.add');
        }
    }
    /**
     * 删除活动
     * @param $id
     */
    public function delete_activity($id){
        //判断活动为当前诊所的
        $rst = M('Activity')->where(array('clinic_id'=>UID,'id'=>$id))->count();
        if(!$rst) $this->ajaxReturn(array('code'=>2,'msg'=>'网络繁忙, 请稍后再试'));
        //删除活动
        $res =  M('Activity')->delete($id);
        if($res){
            $this->ajaxReturn(array('code'=>0,'url'=>U('activity')));
        }else{
            $this->ajaxReturn(array('code'=>1,'msg'=>$this->model->getError()));
        }
    }

}